
package com.scs.application.modules.base.controller;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.scs.application.core.excel.handler.ExcelDictHandlerImpl;
import com.scs.application.core.exceptions.ExportException;
import com.scs.application.core.exceptions.ImportException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.ImportResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.BeanValidators;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.PoiUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.dto.ExcelHospitalSupplierDTO;
import com.scs.application.modules.base.entity.HospitalSupplier;
import com.scs.application.modules.base.request.HospitalSupplierQueryRequest;
import com.scs.application.modules.base.service.HospitalSupplierService;
import com.scs.application.modules.base.vo.ExcelHospitalSupplierVO;
import lombok.AllArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * HospitalSupplier controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/base/hospital_suppliers")
public class HospitalSupplierController extends CrudController<HospitalSupplier, String, HospitalSupplierService> implements ImAndExAbleController<HospitalSupplierQueryRequest> {

    @GetMapping("/page")
    public PageResult page(HospitalSupplierQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(HospitalSupplierQueryRequest request) {
        List<HospitalSupplier> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }


    /**
     * 医院启用供应商，状态设为正常
     *
     * @param id
     * @return
     */
    @PostMapping("enable/{id}")
    public CommonResult enable(@PathVariable("id") String id) {
        service.enable(id);
        return CommonResult.ok("启用成功");
    }

    /**
     * 医院停用供应商，状态设为停用
     *
     * @param id
     * @return
     */
    @PostMapping("disable/{id}")
    public CommonResult disable(@PathVariable("id") String id) {
        service.disable(id);
        return CommonResult.ok("停用成功");
    }

    /**
     * 全部启用
     *
     * @return
     */
    @PostMapping("/all_active")
    public CommonResult allActive() {
        service.allActive();
        return CommonResult.ok("全部启用成功");
    }

    /**
     * 全部停用
     *
     * @return
     */
    @PostMapping("/all_inactive")
    public CommonResult allInactive() {
        service.allInactive();
        return CommonResult.ok("全部停用成功");
    }

    /**
     * 批量保存
     */
    @PutMapping("/batch_save")
    public CommonResult batchSave(@RequestBody @Valid List<HospitalSupplier> hs) {
        Assert.notEmpty(hs, "至少有一条");
        BeanValidators.validateListWithException(validator, hs);

        String hospitalId = UserUtils.getHospitalId();

        ArrayList<HospitalSupplier> list = Lists.newArrayList();

        List<HospitalSupplier> existList = service.list(new HospitalSupplierQueryRequest().setHospitalId(hospitalId));
        for (HospitalSupplier h : hs) {
            long count = existList.stream().filter(o -> o.getSupplierId().equals(h.getSupplierId())).count();
            if (count > 0) {
                continue;
            }
            list.add(h);
        }

        list.stream().forEach(o -> o.setHospitalId(hospitalId).setInactive(HospitalSupplier.DISABLE));

        if (list.isEmpty()) {
            return CommonResult.ok();
        }
        boolean bSuccess = service.saveOrUpdateBatch(list);
        return bSuccess ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
    }

    /**
     * 医院供应商导出数据
     */
    @Override
    public void excelExport(HospitalSupplierQueryRequest request) {
        String fileName = "医院供应商信息" + DateUtils.format(DateUtils.now(), "yyyyMMddHHmmss") + ".xlsx";

        ExportParams params = new ExportParams("医院供应商信息", "医院供应商信息", ExcelType.XSSF);
        params.setDictHandler(ExcelDictHandlerImpl.getInstance());
        request.setHospitalId(UserUtils.isHospital() ? UserUtils.getHospitalId() : null);
        List<ExcelHospitalSupplierVO> list = service.listExcel(request);
        //List<ExcelHospitalSupplierDTO> dtos = Lists.newArrayListWithCapacity(list.size());
        //BeanUtils.copyProperties(list, dtos, ExcelHospitalSupplierDTO.class);
        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), "医院供应商信息", ExcelHospitalSupplierVO.class, list);
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

    /**
     * 医院供应商导出数据模板
     */
    @Override
    public void excelTemplate(HospitalSupplierQueryRequest request) {
        String fileName = "5医院供应商供方关系导入.xlsx";
        ExportParams params = new ExportParams("医院供应商导入模板", "医院供应商信息", ExcelType.XSSF);
        params.setDictHandler(ExcelDictHandlerImpl.getInstance());
        if (UserUtils.isHospital()) {
            params.setExclusions(new String[]{"医院名称"});
        }
        ExcelHospitalSupplierDTO mockData = PoiUtils.mockData(ExcelHospitalSupplierDTO.class);
        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), "医院供应商信息", ExcelHospitalSupplierDTO.class, Lists.newArrayList(mockData));
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

    /**
     * 商品管理 导入数据
     */
    @Override
    public CommonResult<ImportResult> excelImport(MultipartFile file) throws ImportException {
        return CommonResult.ok("导入成功", service.excelImport(file));
    }


    /***
     * @date: 2024/6/24
     * @Description:  添加数据过滤条件
     */
    @Override
    public void fillQueryAuth(QueryWrapper queryWrapper, HospitalSupplier entity) {
        if (UserUtils.isAdmin()) {
            return;
        }
        // 只筛选当前供应商的数据
        boolean isSupplier = false;
        try {
            isSupplier = UserUtils.isSupplier();
        }catch (Exception e) {
        }

        if (isSupplier) {
            queryWrapper.eq("supplier_id", UserUtils.getSupplierId());
        } else {
            queryWrapper.eq("hospital_id", UserUtils.getHospitalId());
        }
    }
}
